<template>
    <div class="wrap">
        <video class="pic-video"
               id="video" width="320" height="320" autoplay></video>
        <canvas id="canvas" width="480" height="320" style="display: none;"></canvas>
        <img v-show="false" :src="imgUrl" id="img" width="480" height="320" style="margin-left: 20px;">
        <div class="tip">
            <div class="content">
                <el-tag type="info">
                    <i class="el-icon-info">Tip:</i>
                </el-tag>
                人脸比对过程中请摘下帽子口罩等物品,将脸对准框内进行比对,以免影响比对结果
            </div>
        </div>
        <div class="current-person">
            当前注册员工:
            <el-tag>
                {{employeeName}}
            </el-tag>
        </div>
        <el-button type="primary" class="bottom-btn-finish" round @click="goChoose">轻触展开员工选择</el-button>
        <el-button type="primary" class="bottom-btn-choose" round @click="goCheck">完成选择,开始比对</el-button>
        <el-drawer
                :show-close="false"
                title="员工选择"
                :visible.sync="drawerShow"
                direction="btt"
                :before-close="handleClose">
            <el-select style="margin-top: 4%;margin-left: 40%" v-model="idValue" placeholder="请选择">
                <el-option
                        v-for="item in employeeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>
        </el-drawer>
    </div>
</template>

<script>
    import {getAllEmployee} from '@/utils/apis/employee'
    import {faceRegister} from "@/utils/apis/face";

    export default {
        name: "FaceRegister",
        data() {
            return {
                imgUrl: '',
                File: '',
                employeeInfo: '',
                idValue: 1,
                employeeList: [],
                drawerShow: false,
                employeeName: '',
                mediaStreamTrack: '',
                context: ''
            }
        },
        mounted() {
            this.initData()
            this.initCamera()
            // setTimeout(() => {
            //     this.takePhoto()
            //     this.confirmSubmit()
            // }, 3000)
            // this.$message.info('三秒后开始对比人脸,请将人脸对齐框内')
        },
        methods: {
            async initData() {
                await getAllEmployee().then(res => {
                    this.employeeList = res.data.data
                    this.employeeInfo = this.employeeInfo = JSON.stringify(this.employeeList[0])
                    this.idValue = this.employeeList[0].id
                    this.employeeName = this.employeeList[0].name

                })
            },
            goChoose() {
                this.drawerShow = true
            },
            //开始比对
            goCheck() {
                this.$message.info('三秒后开始对比人脸,请将人脸对齐')
                setTimeout(() => {
                    this.takePhoto()
                    this.confirmSubmit()
                }, 3000)
            },
            //关闭前钩子
            handleClose() {
                this.drawerShow = false
                this.employeeList.forEach(emp => {
                    if (emp.id === this.idValue) {
                        this.employeeInfo = JSON.stringify(emp)
                        this.employeeName = emp.name
                    }
                })
            },
            //初始化拍照
            initCamera() {
                let self = this
                navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia
                if (navigator.getUserMedia) {
                    //调用用户媒体设备, 访问摄像头
                    navigator.getUserMedia({video: {width: 480, height: 320}}, stream => {
                        this.mediaStreamTrack = stream
                        var video = document.querySelector('video');
                        video.srcObject = stream;
                        self.streamPicture = stream; //关闭摄像头需要用
                        video.onloadedmetadata = function (e) {
                            video.play();
                        }
                    }, error => {
                        self.$message.error('访问用户媒体设备失败:' + error.name)
                    })
                } else {
                    self.$message.error('不支持访问用户媒体');
                }

            },
            //拍照点击
            takePhoto() {
                let canvas = document.getElementById('canvas');
                let context = canvas.getContext('2d');
                this.context = context
                context.drawImage(video, 0, 0, 480, 320);
                // 获取图片base64链接
                var image = canvas.toDataURL('image/png');
                // 定义一个img
                var img = document.getElementById("img");
                //设置属性和src
                //img.id = "imgBoxxx";
                img.src = image;
                this.imgUrl = image
                // console.log(this.imgUrl)
                //将图片添加到页面中
                // document.body.appendChild(img);
                function dataURLtoFile(dataurl, filename) {
                    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new File([u8arr], filename, {type: mime});
                }

                this.File = dataURLtoFile(image, 'employee.png');
                return dataURLtoFile(image, 'employee.png');
            },
            //确认上传
            async confirmSubmit() {
                // debugger;
                if (this.File === '') { //如果不点击拍照
                    this.$message.warning(`请先拍照再点击确定`);
                    return;
                }
                const formData = {
                    file: this.File,
                    employee: this.employeeInfo
                }
                try {
                    //发送网络请求
                    await faceRegister(formData).then(res => {
                        this.$message.success(res.data.data)

                    })
                } catch (e) {
                    setTimeout(() => {
                        console.log('再次进行对比')
                        this.takePhoto()
                        this.confirmSubmit()
                    }, 1000)
                }
            },
            closeVideo() {
                this.mediaStreamTrack.getVideoTracks().forEach(track => {
                    track.stop();
                    // this.context.clearRect(0, 0, this.context.width, this.context.height);//清除画布
                });
            },
        },
        destroyed() {
            this.closeVideo()
        }
    }
</script>

<style scoped>
    .wrap {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .pic-video {
        margin-top: 1%;
        border-radius: 50%;
        object-fit: cover;
        box-shadow: rgba(0, 0, 0, 0.3) 1px 1px 10px;
    }

    .tip {
        margin-top: 3%;
        width: 45%;
        height: 10%;
    }

    .bottom-btn-finish {
        position: fixed;
        bottom: 10%;
        left: 45%;
    }

    .bottom-btn-choose {
        position: fixed;
        bottom: 10%;
        left: 58%;
    }

    .current-person {
        font-size: 20px;
        text-align: center;
    }
</style>